import React from 'react';
import { Table, Button, Balloon, Message, PopConfirm } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { ButtonIcon } from '@alife/devops-ui';
import utils from 'utils';
import { navigateOpen } from 'utils/router';
import Filter from './filter';
import MoreBtn from './moreBtn';
import exceed from 'utils/apimap';
import ListEmpty from 'atComponents/ListEmpty';
import track from 'utils/track';
import docs from 'utils/docs';
import intl from '../../../../../../../../../../locale';

export default class Record extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoadingList: true,
      list: [],
      page: 1,
      total: 0,
      per_page: 10,
      sort: 'desc',
      order_by: 'gmt_create',
      begin_date: '',
      end_date: '',
      author_ids: '',
      users: [],
      visible: false,
    };
  }

  componentDidMount() {
    this.getLfsList(1);
  }

  getLfsList = (page) => {
    this.setState({
      isLoadingList: true,
    });

    const { per_page, sort, order_by, begin_date, end_date, author_ids } = this.state;
    const data = {
      page,
      per_page,
      sort,
      order_by,
      begin_date,
      end_date,
      author_tb_ids: author_ids,
    };

    const { pathResource } = window.FORCE;

    exceed
      .fetch({
        api: 'project.lfs.list.get',
        params: {
          projectId: pathResource.id,
        },

        data,
      })
      .then((result) => {
        const list = result.slice(1);
        this.setState({
          list,
          total: result[0].amount,
          page,
          isLoadingList: false,
        });
      })
      .fail(() => {
        this.setState({
          isLoadingList: false,
        });
      });
  };

  renderOid = (value) => {
    return (
      <Balloon.Tooltip trigger={<div className="table-cell-one-line">{value}</div>} align="t">
        {value}
      </Balloon.Tooltip>
    );
  };

  handleDownload = (id) => {
    track({
      action: 'download_lfs',
      page: 'Repo-Settings-LFS',
      type: '',
      control: '',
    });

    const { pathResource } = window.FORCE;
    exceed
      .fetch({
        api: 'project.lfs.single.download',
        params: {
          projectId: pathResource.id,
          lfsId: id,
        },
      })
      .then((result) => {
        const { download_link } = result;
        navigateOpen(download_link, '_self');
      });
  };

  renderActions = (value, index, record) => {
    const downloadBtn = (
      <Button
        type="primary"
        text
        onClick={() => {
          this.handleDownload(record.id);
        }}
      >
        {intl.get({ id: 'code-assets.containers.lfsList.Download', defaultMessage: '下载' })}
      </Button>
    );

    return [
      downloadBtn,
      <MoreBtn
        record={record}
        getLfsInfo={this.props.getLfsInfo}
        getLfsList={() => {
          this.getLfsList(1);
        }}
      />,
    ];
  };

  renderAuthor = (value) => {
    const { avatar, name } = value || {};
    return (
      <Balloon.Tooltip
        trigger={
          <div className={'author-info table-cell-one-line'}>
            <img src={avatar} />
            {name}
          </div>
        }
        align="t"
        text={name}
      />
    );
  };

  renderSize = (value) => {
    return utils.getSizeStr(value);
  };

  renderTime = (value) => {
    return utils.getBeautyTime(value);
  };

  updateRecordParams = (tableParams) => {
    this.setState(
      {
        ...tableParams,
      },

      () => {
        this.getLfsList(1);
      },
    );
  };

  onSelectRows = (row) => {
    this.setState({
      delBtnEnable: !!row.length,
      selectRows: row,
    });
  };

  deleteLfs = (lfsIds) => {
    const { pathResource } = window.FORCE;
    return exceed.fetch({
      api: 'project.lfs.batch.delete',
      params: {
        projectId: pathResource.id,
      },

      data: {
        lfsIds,
      },
    });
  };

  onConfirm = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    track({
      action: 'delete_lfs_file',
      page: 'Repo-Settings-LFS',
      type: '',
      control: '',
    });

    const { getLfsInfo } = this.props;
    const { selectRows } = this.state;
    this.deleteLfs(selectRows)
      .then((result) => {
        this.setState({
          visible: false,
          submitting: false,
          selectRows: [],
        });
        const { success } = result;
        if (success) {
          Message.success({
            title: intl.get({
              id: 'code-assets.containers.lfsList.GitLfsDeleted',
              defaultMessage: 'Git LFS 文件删除成功',
            }),
          });

          // 删除成功后更新表格以及容量
          this.getLfsList(1);
          getLfsInfo && getLfsInfo();
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.containers.lfsList.UnableToDeleteTheGit',
              defaultMessage: 'Git LFS 文件删除失败',
            }),
          });
        }
      })
      .catch(() => {
        this.setState({ submitting: false });
        Message.error({
          title: intl.get({
            id: 'code-assets.containers.lfsList.UnableToDeleteTheGit.1',
            defaultMessage: 'Git LFS 删除失败',
          }),
        });
      });
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const {
      isLoadingList,
      list,
      page,
      total,
      begin_date,
      end_date,
      author_ids,
      users,
      delBtnEnable,
      visible,
      selectRows,
    } = this.state;
    const { lfsInfo } = this.props;

    return (
      <div className="lfs-table-container">
        {lfsInfo.used ? (
          <>
            <div className="lfs-table-filter">
              {/* 自所以重新包一下，主要是因为Button被disabled时，Button内的气泡trigger hover失效 */}
              <div className="lfs-table-list-delete-btn">
                <PopConfirm
                  triggerType="click"
                  align="b"
                  type="warning"
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.ConfirmDeletion',
                    defaultMessage: '确认删除',
                  })}
                  needAdjust
                  content={intl.get({
                    id: 'code-assets.containers.lfsList.AreYouSureYouWant',
                    defaultMessage: '确定要删除该文件么？',
                  })}
                  onConfirm={() => {
                    this.onConfirm();
                  }}
                  confirmProps={{ loading: this.state.submitting }}
                  onCancel={this.onCancel}
                  popupProps={{ loading: this.state.submitting }}
                  visible={visible}
                  trigger={
                    <Button
                      type="primary"
                      warning
                      disabled={!delBtnEnable}
                      onClick={() => {
                        this.setState({ visible: true });
                      }}
                    >
                      {intl.get({
                        id: 'code-assets.containers.lfsList.Delete',
                        defaultMessage: '删除',
                      })}
                      <span style={{ display: 'inline-block', width: 20 }} />
                    </Button>
                  }
                />
                <span className="lfs-table-list-delete-btn-tip">
                  <Balloon
                    closable={false}
                    trigger={
                      <ButtonIcon
                        size="small"
                        name="question-line"
                        style={{ display: 'inline-block', color: '#fff' }}
                      />
                    }
                    align="t"
                  >
                    <a target="_blank" href={docs('lfs-delete')} rel="noreferrer">
                      {intl.get({
                        id: 'code-assets.containers.lfsList.WhatIsTheImpactOf',
                        defaultMessage: '删除文件有什么影响？',
                      })}
                    </a>{' '}
                  </Balloon>
                </span>
              </div>
              <span style={{ flex: 1 }} />
              <Filter
                tableParams={{
                  begin_date,
                  end_date,
                  author_ids,
                }}
                updateRecordParams={this.updateRecordParams}
                users={users}
              />
            </div>
            <div className="lfs-table-detail">
              <Table
                primaryKey="id"
                className={'no-border-table'}
                hasBorder={false}
                dataSource={list}
                loading={isLoadingList}
                rowSelection={{
                  onChange: this.onSelectRows,
                  selectedRowKeys: selectRows,
                }}
                emptyContent={
                  <ListEmpty
                    content={intl.get({
                      id: 'code-assets.containers.lfsList.NoData',
                      defaultMessage: '暂无数据',
                    })}
                    imgType="search"
                    className="table-list-empty"
                    size="small"
                  />
                }
              >
                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.FileOid',
                    defaultMessage: '文件 OID',
                  })}
                  dataIndex="oid"
                  cell={this.renderOid}
                  width={150}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.FileType',
                    defaultMessage: '文件类型',
                  })}
                  width={100}
                  dataIndex="file_suffix"
                />
                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.FileSize',
                    defaultMessage: '文件大小',
                  })}
                  width={100}
                  dataIndex="file_size"
                  cell={this.renderSize}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.Operator',
                    defaultMessage: '操作人',
                  })}
                  width={140}
                  dataIndex="author"
                  cell={this.renderAuthor}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.OperationTime',
                    defaultMessage: '操作时间',
                  })}
                  dataIndex="commit_time"
                  width={170}
                  cell={this.renderTime}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.lfsList.Operation',
                    defaultMessage: '操作',
                  })}
                  dataIndex={'oid'}
                  width={130}
                  cell={this.renderActions}
                  lock="right"
                />
              </Table>
              <Pagination
                onChange={this.getLfsList}
                current={page}
                total={total}
                showJump={false}
                hideOnlyOnePage
              />
            </div>
          </>
        ) : (
          <ListEmpty
            size="small"
            type="card"
            content="暂无 LFS 大文件"
            description={
              <a href={docs('lfs')} target="_blank" rel="noreferrer">
                {intl.get({
                  id: 'code-assets.containers.lfsList.HowDoIUseGit',
                  defaultMessage: '如何使用 Git LFS 服务？',
                })}
              </a>
            }
            image="none"
            className="no-content no-btns"
          />
        )}
      </div>
    );
  }
}
